package com.openharmony.filepicker.config;

import com.openharmony.filepicker.engine.ImageLoadController;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class FilePickerManager {

    private static volatile FilePickerManager filePickerManager;

    public static final int REQUEST_CODE = 10401;
    public static final int RESULT_CANCELED = 0;
    public static final int RESULT_OK = -1;
    private WeakReference<Ability> contextRef;
    private WeakReference<AbilitySlice> fragmentRef;
    private FilePickerConfig config;
    private List<String> dataList = new ArrayList<>();

    private FilePickerManager() { }

    public static FilePickerManager INSTANCE() {
        if (filePickerManager == null) {
            synchronized (FilePickerManager.class) {
                if (filePickerManager == null) {
                    filePickerManager = new FilePickerManager();
                }
            }
        }
        return filePickerManager;
    }

    public FilePickerConfig from(Ability ability) {
        reset();
        this.contextRef = new WeakReference<>(ability);
        config = new FilePickerConfig(this);
        return config;
    }

    public FilePickerConfig from(AbilitySlice slice) {
        reset();
        this.fragmentRef = new WeakReference<>(slice);
        this.contextRef = new WeakReference<>(slice.getAbility());
        config = new FilePickerConfig(this);
        return config;
    }

    /**
     * 保存数据@param list List<String>到本类中
     */
    public void saveData(List<String> list) {
        dataList = list;
    }

    public List<String> obtainData(boolean release) {
        if (release) {
            release();
        }
        return dataList;
    }

    public List<String> obtainData() {
        return this.obtainData(false);
    }

    private void release() {

    }

    private void reset() {
        if (contextRef != null) {
            contextRef.clear();
        }

        if (fragmentRef != null) {
            fragmentRef.clear();
        }
        ImageLoadController.INSTANCE().reset();
    }

    public WeakReference<Ability> getContextRef() {
        return contextRef;
    }

    public void setContextRef(WeakReference<Ability> contextRef) {
        this.contextRef = contextRef;
    }

    public WeakReference<AbilitySlice> getFragmentRef() {
        return fragmentRef;
    }

    public void setFragmentRef(WeakReference<AbilitySlice> fragmentRef) {
        this.fragmentRef = fragmentRef;
    }

    public FilePickerConfig getConfig() {
        return config;
    }

    public void setConfig(FilePickerConfig config) {
        this.config = config;
    }
}
